<script setup lang="ts">
 import { ref } from  'vue'
 import { onShow,onLoad } from '@dcloudio/uni-app'
 import {
   formValidate,
   hideLoading,
   msg, picturePreview,
   showLoading,
   showModal
 } from '@/utils/tools'
 import { mechanismInfo, transfer, transferTips } from '@/api/auth'
 import { drawRoundedRect, drawText, getImgBase64 } from '@/utils/canvas'
 const modalShow = ref(false)
 const mobile = ref('')
 const mechanism = ref({})
 const context = ref()
 const tempFilePath = ref()
 const canvasShow = ref(true)
 const { pixelRatio=1 } = uni.getSystemInfoSync()
 onLoad(() => {
   context.value = uni.createCanvasContext('canvasId')
 })
 onShow(() => {
   mechanismInfo().then(res => {
     if(res.code == 200){
       res.data.qualificationDocuments = res.data.qualificationDocuments ? JSON.parse( res.data.qualificationDocuments): ''
       mechanism.value = res.data
       if(mechanism.value.institutionalStatusEnum == 1){
         drawContext()
       }
     }
   })
 })
 const drawContext = async () => {
   // 填充背景
   try {
     showLoading()
     await drawBgImg()
     await drawTxt()
     context.value.draw(true, () => {
       uni.canvasToTempFilePath({
         canvasId:'canvasId',
         quality:1,
         width:uni.upx2px(600),
         height:uni.upx2px(680),
         destWidth:uni.upx2px(600) * pixelRatio,
         destHeight:uni.upx2px(680) * pixelRatio,
         success:(res:any) => {
           tempFilePath.value = res.tempFilePath
           const time = setTimeout(() => {
             canvasShow.value = false
             clearTimeout(time)
           },500)
         }
       })
     })

   } finally {
     hideLoading()
   }
 }
 const drawTxt = async () => {
   const ctx = context.value
   // 绘制文字
   drawText({
     ctx,
     text: mechanism.value.companyName,
     fillStyle: '#000000',
     fontSize: 20,
     x: (uni.upx2px(600) / 2),
     y: uni.upx2px(600) + 20,
     center: true
   })
 }

 // 绘制图片
 const drawBgImg = async () => {
   const imgTemp = uni.env.USER_DATA_PATH + `/${new Date().getTime()}-temp.png`
   const { imgUrl, imageWidth, imageHeight } = await getImgBase64({
     src: mechanism.value.qrCode,
     canvasWidth: 600,
     filePath: imgTemp
   })
   drawRoundedRect(context.value, 0,0,uni.upx2px(600),uni.upx2px(680),{
     fillColor:"#EBF4F4",
     leftBottom: true,
     leftTop: true,
     rightBottom: true,
     rightTop: true,
     r: 5
   })
   context.value.drawImage(imgUrl, (uni.upx2px(600 - 560)) / 2, 10, uni.upx2px(560), uni.upx2px(560))
 }
 const confirm = () => {
   formValidate({mobile:mobile.value},{mobile:{message: '请输入手机号', patternType:'phone'}}).then(() => {
     transferTips({mobile:mobile.value}).then(res => {
       if(res.code == 200){
         showModal({
           content:res.data.tips,
           success:(_res)=>{
             if(_res.confirm){
               transfer({mobile:mobile.value}).then(transferRes => {
                 if(transferRes.data){
                   uni.navigateBack({delta:1})
                 }
               })
             }
           }
         })
       }
     })
   })
 }
 const cancel = () => {
   modalShow.value = false
   mobile.value = ''
 }

 const navigatorClick = (url:any) => {
   uni.navigateTo({url})
 }

 //保存图片
 const saveImage = () => {
   showLoading('保存中...')
   let fileName = mechanism.value.companyName + '_' + new Date().valueOf();
   let filePath = uni.env.USER_DATA_PATH + '/' + fileName + '.jpg'
   uni.saveImageToPhotosAlbum({
     filePath: tempFilePath.value,
     success() {
       msg('已保存至您的相册')
       hideLoading()
     },
     fail(err:any) {
       hideLoading()
       if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
         showModal({content:'需要您授权保存相册', success: modalSuccess => {
             uni.openSetting({
               success(settingdata:any) {
                 if (!settingdata.authSetting['scope.writePhotosAlbum']) {
                   msg('权限获取失败',false)
                 }
               }
             })
           }})
       }
     }
   })
 }
</script>

<template>
  <view class="mechanism-body">
    <xx-title title="机构信息"/>
    <view class="school-tips" v-if="mechanism.institutionalStatusEnum == 1">
      <view class="school-left">
        <up-icon name="info-circle-fill" color="#e6a23c" size="14"></up-icon>
      </view>
      <view class="school-right">
        <view class="tips">温馨提示</view>
        <view class="tips-content">
          <view>1. 长按保存二维码（此二维码为该机构专属二维码）。</view>
          <view>2. 二维码分享给机构学员或其家长用微信扫码报名缴费。</view>
        </view>
      </view>
    </view>
    <view class="mechanism-title" :class="{'is-audio':mechanism.institutionalStatusEnum == 0 || mechanism.institutionalStatusEnum == -1}">{{ mechanism.companyName }}<text v-if="mechanism.institutionalStatusEnum != 1">({{ mechanism.institutionalStatusEnumDesc }})</text></view>
    <view class="mechanism-info-body">
      <view class="mechanism-tips" v-if="mechanism.institutionalStatusEnum == 1">
        <up-icon name="info-circle-fill" color="#818496" size="14"></up-icon>
        <text>请长按二维码或保存图片扫码</text>
      </view>
      <view class="mechanism-qrcode" v-if="mechanism.institutionalStatusEnum == 1">
        <canvas class="canvas" v-if="canvasShow" style="width:600rpx;height:680rpx" canvas-id="canvasId"></canvas>
        <image :show-menu-by-longpress="true" v-else :src="tempFilePath" />
      </view>
      <view class="mechanism-qrcode" v-else>
        <view class="mechanism-tip">
          <view style="text-align: center" v-if="mechanism.institutionalStatusEnum == 0">
            <up-icon name="info-circle-fill" color="#D05357" size="100"></up-icon>
            <div class="tips-text">正在审核</div>
          </view>
          <view style="text-align: center" v-if="mechanism.institutionalStatusEnum == -1">
            <up-icon name="close-circle-fill" color="#D05357" size="100"></up-icon>
            <div class="tips-text">未通过审核，请修改信息后再次提交</div>
          </view>
        </view>
      </view>
      <view class="mechanism-info">
        <view class="mechanism-info-item" v-if="mechanism.contactPhoneNumber">
          <view class="info-item-label">联系电话：</view>
          <view class="info-item-value">{{mechanism.contactPhoneNumber}}</view>
        </view>
        <view class="mechanism-info-item" v-if="mechanism.provinceName">
          <view class="info-item-label">机构地址：</view>
          <view class="info-item-value">{{mechanism.provinceName}}/{{mechanism.cityName}}/{{mechanism.countyName}}</view>
        </view>
        <view class="mechanism-info-item" v-if="mechanism.qualificationDocuments">
          <view class="info-item-label">营业执照：</view>
          <view class="info-item-value">
            <image @click="picturePreview(0,[mechanism.qualificationDocuments[0].fullUrl])" :src="mechanism.qualificationDocuments[0].fullUrl"/>
          </view>
        </view>
      </view>
      <view class="mechanism-btn">
        <view class="btn-item" @click="saveImage" v-if="mechanism.institutionalStatusEnum == 1">
          <image :src="`${$Prefix}/public/images/smallImage/save.png`" mode="widthFix"/>
          <view class="title">保存图片</view>
        </view>
        <view class="btn-item" @click="navigatorClick('/pages/teamSignUp/teamSignUp')" v-if="mechanism.institutionalStatusEnum == -1">
          <image :src="`${$Prefix}/public/images/smallImage/edit.png`" mode="widthFix"/>
          <view class="title">修改信息</view>
        </view>
        <view class="btn-item" @click="modalShow = true" v-if="mechanism.institutionalStatusEnum == 1">
          <image :src="`${$Prefix}/public/images/smallImage/binding.png`" mode="widthFix"/>
          <view class="title">更改绑定</view>
        </view>
        <view class="btn-item" @click="navigatorClick('/pages/teamList/teamList')" v-if="mechanism.institutionalStatusEnum == 1">
          <image :src="`${$Prefix}/public/images/smallImage/signup-list.png`" mode="widthFix"/>
          <view class="title">报名情况</view>
        </view>
      </view>
    </view>
  </view>
  <up-modal :show="modalShow"  v-if="modalShow" :showCancelButton="true" @cancel="cancel" @confirm="confirm">
    <view class="modify">
      <view class="title">修改绑定用户</view>
      <view class="form-item">
        <view class="item-label">更改手机号：</view>
        <view class="item-value">
          <input class="uni-input" v-model="mobile" focus placeholder="请输入手机号" />
        </view>
      </view>
    </view>
  </up-modal>
</template>

<style scoped lang="scss">
.modify{
  .title{
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 40rpx;
  }
  .form-item{
    width: 100%;
    display: flex;
    align-items: center;
    .item-label{
      width: 210rpx;
    }
    .item-value{
      width: calc(100% - 210rpx);
    }
  }
}
.mechanism-body{
  background-color: #F5F5F5;
  padding: 20rpx;
  box-sizing: border-box;
  min-height: 100vh;
  .mechanism-title{
    padding: 20rpx;
    width: 100%;
    box-sizing: border-box;
    color: #FFFFFF;
    text-align: center;
    font-weight: 500;
    font-size: 32rpx;
    border-radius: 8rpx 8rpx 16rpx 16rpx;
    background: linear-gradient(270deg, #92C75B 0%, #89BA55 100%);
    text{
      font-size: 28rpx;
      margin: 0 10rpx;
    }
    .is-audio{
      background-color: linear-gradient(270deg, #f31919 0%, #cb0202 100%);
    }
  }
  .mechanism-info-body{
    padding: 40rpx 20rpx;
    box-sizing: border-box;
    background-color: #FFFFFF;
    border-radius: 16rpx 16rpx 8rpx 8rpx;
    .mechanism-tips{
      display: flex;
      align-items: center;
      justify-content: center;
      text{
        font-size: 28rpx;
      }
    }
    .mechanism-qrcode{
      width: 600rpx;
      height: 670rpx;
      margin: 20rpx auto;
      position: relative;
      .canvas{
        opacity: 0;
        position: absolute;
        z-index: -1;
      }
      image{
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }
      .mechanism-tip{
        display:flex;
        align-items:center;
        justify-content:center;
        width:100%;
        height:100%;
        ::v-deep.u-icon{
          display: inline-block;
          margin-bottom: 20rpx;
        }
        .tips-text{
          font-size: 32rpx;
          text-align: center;
        }
      }
    }
    .mechanism-info{
      background-color: #F7F7F7;
      padding: 20rpx 24rpx;
      border-radius: 16rpx;
      .mechanism-info-item{
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        padding-bottom: 20rpx;
        &:last-child{
          padding-bottom: 0;
        }
        .info-item-label{
          color: #505363;
          font-size: 24rpx;
        }
        .info-item-value{
          color: #505363;
          font-size: 24rpx;
          image{
            width: 150rpx;
            height: 150rpx;
            border-radius: 10rpx;
          }
        }
      }
    }
    .mechanism-btn{
      margin-top: 20rpx;
      padding-top: 40rpx;
      border-top: 1rpx solid #F5F5F5;
      display: flex;
      justify-content: center;
      align-items: center;
      &:last-child{
        border-right: none;
      }
      .btn-item{
        width: calc(100% / 3);
        text-align: center;
        border-right: 1px solid #F7F7F7;
        &:last-child{
          border-right: none;
        }
        image{
          width: 30rpx;
        }
        .title{
          color: #818496;
          font-size: 24rpx;
        }
      }
    }
  }
}
.school-tips{
  width: 100%;
  padding: 12rpx 16rpx;
  margin-bottom: 20rpx;
  box-sizing: border-box;
  border-radius: 8rpx;
  position: relative;
  display: flex;
  background-color: #fdf6ec;
  color: #e6a23c;
  .school-right{
    width: calc(100% - 28rpx);
    margin-left: 4rpx;
    font-size: 26rpx;
    .tips{
      font-size: 28rpx;
      margin-bottom: 10rpx;
    }
  }
}
</style>
